package com.smartcruise.util.network.baseApi;

import com.smartcruise.util.network.RetrofitFactory;

import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;


/**
 * Created by FengChaoQun
 * on 2018/2/2
 */

public class NetApiObservableFactory {
    private NormalPostAPI normalPostAPI = RetrofitFactory.getRetrofit().create(NormalPostAPI.class);
    private NormalGetAPI normalGetAPI = RetrofitFactory.getRetrofit().create(NormalGetAPI.class);
    private MultipartApi multipartApi = RetrofitFactory.getRetrofit().create(MultipartApi.class);
    private NormalPutAPI normalPutAPI = RetrofitFactory.getRetrofit().create(NormalPutAPI.class);

    private NetApiObservableFactory() {

    }

    public static NetApiObservableFactory getInstance() {
        return NetApiObservableFactory.InstanceHolder.Instance;
    }

    public Observable<ResponseBody> normalPostObservable(String url, Map<String, Object> data) {
        return normalPostAPI.post(url, data);
    }

    public Observable<ResponseBody> normalGetObservable(String url) {
        return normalGetAPI.start(url);
    }

    public Observable<ResponseBody> normalMultipartObservable(String url, Map<String, RequestBody> requestBodyMap) {
        return multipartApi.post(url, requestBodyMap);
    }

    public Observable<ResponseBody> normalPutObservable(String url, Map<String, Object> data) {
        return normalPutAPI.put(url, data);
    }

    /**
     * description:构造一个Multipart请求的Observable 应为可能需要压缩图片 所以将构造Map<String, RequestBody>这一过程放到异步线程中处理
     * 避免主线程阻塞
     *
     * @param url                  请求的地址
     * @param multipartBodyBuilder Map<String, RequestBody>的构造器
     */

    public Observable<ResponseBody> normalMultipartObservable(final String url, final MultipartBodyBuilder multipartBodyBuilder) {
        return Observable.create(new ObservableOnSubscribe<Map<String, RequestBody>>() {
            @Override
            public void subscribe(ObservableEmitter<Map<String, RequestBody>> observableEmitter) throws Exception {
                Map<String, RequestBody> map = multipartBodyBuilder.build();
                observableEmitter.onNext(map);
                observableEmitter.onComplete();
            }
        }).flatMap(new Function<Map<String, RequestBody>, ObservableSource<ResponseBody>>() {
            @Override
            public ObservableSource<ResponseBody> apply(Map<String, RequestBody> stringRequestBodyMap) throws Exception {
                return NetApiObservableFactory.getInstance().normalMultipartObservable(url, stringRequestBodyMap);
            }
        });
    }

    private static class InstanceHolder {
        private static NetApiObservableFactory Instance = new NetApiObservableFactory();
    }

}
